<?php

namespace App\Traits;

use Illuminate\Http\JsonResponse;

trait ApiResponseTrait
{
    /**
     * 成功返回JSON
     * @param array $data
     * @param string $message
     * @param int $code
     * @return JsonResponse
     */
    public static function success(array $data = [], string $message = '操作成功', int $code = 0): JsonResponse
    {
        return response()->json(
            [
                'code' => $code,
                'message' => $message,
                'content' => $data,
            ]
        );
    }

    /**
     * 错误返回JSON
     * @param string $message
     * @param int $code
     * @return JsonResponse
     */
    public static function error(string $message = '操作失败', int $code = 1): JsonResponse
    {
        return response()->json(
            [
                'code' => $code,
                'message' => $message,
            ]
        );
    }


    /**
     * 错误跳转JSON
     * @param string $redirect_url
     * @param string $message
     * @param int $code
     * @return JsonResponse
     */
    public static function error_redirect(string $message = '操作失败', string $redirect_url = '', int $code = 301): JsonResponse
    {
        return response()->json(
            [
                'code' => $code,
                'message' => $message,
                'redirect_url' => $redirect_url,
            ]
        );
    }


    /**
     * @param string $message
     * @param int $code
     * @return JsonResponse
     */
    public static function invalid(string $message = '登录状态失效,请重新登录', int $code = 401): JsonResponse
    {
        return response()->json(
            [
                'code' => $code,
                'message' => $message,
            ],
            401
        );
    }

    /**
     * @param string $message
     * @param int $code
     * @return JsonResponse
     */
    public static function forbidden(string $message = '非法请求', int $code = 403): JsonResponse
    {
        return response()->json(
            [
                'code' => $code,
                'message' => $message,
            ],
            403
        );
    }
}
